package com.acerola.downloader.core;

import com.acerola.downloader.constant.Constant;
import com.acerola.downloader.util.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * @program: MultithreadedDownloader
 * @description: 分块下载
 * @author: Acerola
 * @create: 2022-05-12 09:29
 **/
public class DownloaderTask implements Callable {
    private Logger logger = LoggerFactory.getLogger(DownloaderTask.class);
    private String url;
    //下载的起始位置
    private long startPos;
    //下载的结束位置
    private long endPos;
    //标识下载部分
    private int part;

    private CountDownLatch countDownLatch;

    private String path;

    public DownloaderTask(String url, long startPos, long endPos, int part, CountDownLatch countDownLatch,String path) {
        this.url = url;
        this.startPos = startPos;
        this.endPos = endPos;
        this.part = part;
        this.countDownLatch = countDownLatch;
        this.path = path;
    }

    @Override
    public Boolean call() throws Exception {
        //获取文件名
        String httpFileName = HttpUtils.getHttpFileName(url);
        //分块
        httpFileName = httpFileName + ".temp" + part;
        //下载路径
        httpFileName = path + httpFileName;
        //获取分块下载的链接
        HttpURLConnection urlConnection = HttpUtils.getURLConnection(url, startPos, endPos);
        try (
                InputStream input = urlConnection.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(input);
                RandomAccessFile accessFile = new RandomAccessFile(httpFileName, "rw");
        ) {
            byte[] buffer = new byte[Constant.BYTE_SIZE];
            int len = 0;
            while ((len = bis.read(buffer)) != -1) {
                //1秒内下载数据之和.通过原子类进行操作
                DownloaderInfoThread.downSize.add(len);
                accessFile.write(buffer, 0, len);

            }

        } catch (FileNotFoundException e) {
            logger.error("下载文件不存在{}", url);
            return false;
        } catch (Exception e) {
            logger.error("下载出现异常");
            return false;
        }finally {
            urlConnection.disconnect();
            countDownLatch.countDown();
        }
        return null;
    }
}
